#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#该备份脚本仅用于导入sql文件，需要先创建建目标库
#如果检测到目标库不存在则会退出
import os
import time
import datetime
DB_HOST = '10.0.14.214'
DB_USER = 'root'
DB_USER_PASSWD = 'root'
DB_NAME = '/opt/dbbackup/dbname.txt'
BACKUP_PATH = '/opt/dbbackup/mysql/'
#sql文件所在目录
DATETIME = '20190904-191239'
TODAYBACKUPPATH = BACKUP_PATH + DATETIME
#检查数据库是否创建,返回检查结果
def db_check(dbname):
	checkcmd = "/usr/local/mysql/bin/mysql -u" +DB_USER + " -p"+DB_USER_PASSWD+ " -h"+DB_HOST+" -e " '"show databases like \'%s\';"'"|grep %s "  % (dbname, dbname)
	s = os.system(checkcmd)
	return s
#定义执行备份脚本，读取文件中的数据库名称，注意按行读写，如果数据库已创建则正常导入，否则将退出本次循环，
def run_import():
	in_file = open(DB_NAME,"r")
	for dbname in in_file.readlines():
		dbname = dbname.strip()
		check_result = db_check(dbname)
		if check_result  == 0:
			print("\033[34mDatabase %s already exists ...\033[0m" % dbname)
		else:
			print("\033[31mDatabase %s does not exist,please first create\033[0m " % dbname)
			continue
		print("\033[34mNow starting import database %s ...\033[0m" % dbname)
		importcmd = "/usr/local/mysql/bin/mysql -u" +DB_USER + " -p"+DB_USER_PASSWD+ " -h"+DB_HOST+" " +dbname+" < "+TODAYBACKUPPATH +"/"+dbname+".sql"
		print(importcmd)
		os.system(importcmd)
	file1.close()

#备份数据库文件存在就执行导入，否则退出
if os.path.exists(DB_NAME):
	file1 = open(DB_NAME)
	print("\033[34mStarting import of all db listed in file \033[0m"+DB_NAME)
	run_import()
	print("\033[32mImport success!\033[0m")
else:
	print("\033[31mDatabase file not found..\033[0m")
	exit()
